package com.lex.cheeseStrip.ui;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.anthonycr.grant.PermissionsManager;
import com.anthonycr.grant.PermissionsResultAction;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.dh.cheesestrip.HttpUtil.HttpSender;
import com.dh.cheesestrip.Util.AndroidUtil;
import com.dh.cheesestrip.Util.ImageUtil;
import com.dh.cheesestrip.Util.LogUtil;
import com.dh.cheesestrip.Util.ScreenUtil;
import com.dh.cheesestrip.Util.SpUtil;
import com.dh.cheesestrip.Util.StringUtil;
import com.dh.cheesestrip.Util.jsonUtil;
import com.lex.cheeseStrip.R;
import com.lex.cheeseStrip.app.BaseAct;
import com.lex.cheeseStrip.app.WebSocketCallback;
import com.lex.cheeseStrip.bean.Location;
import com.lex.cheeseStrip.bean.User;
import com.lex.cheeseStrip.bean.WebSocketMsg;
import com.lex.cheeseStrip.util.WebSocketUtil;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerClickListener;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import static com.dh.cheesestrip.Util.jsonUtil.json2Bean;
import static com.dh.cheesestrip.Util.jsonUtil.toJson;
import static com.lex.cheeseStrip.R.id.btn_lv;

public class MainActivity extends BaseAct {

    @BindView(R.id.sdv)
    ImageView mSdv;
    @BindView(R.id.tv)
    TextView mTv;
    @BindView(R.id.activity_main)
    LinearLayout mActivityMain;
    @BindView(R.id.sdv1)
    ImageView mSdv1;
    @BindView(R.id.btn)
    Button mBtn;
    @BindView(R.id.btn_calendar)
    Button mBtnCalendar;
    @BindView(btn_lv)
    Button mBtnLv;
    @BindView(R.id.btn_img)
    Button mBtnImg;
    String s;
    @BindView(R.id.btn_send_msg)
    Button mBtnSendMsg;
    @BindView(R.id.edt_msg)
    EditText mEdtMsg;

    @BindView(R.id.banner)
    Banner mBanner;

    @BindView(R.id.baidu)
    Button baidu;
    @BindView(R.id.btn_pop)
    Button btnPop;

    private WebSocketClient mWebSocketClient;
    private StringBuffer socketBuffter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        init(this);

        Set<String> set = new HashSet<>();
        set.add("客户");
        JPushInterface.setAliasAndTags(getActivity(), "13228898364", set, new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {
                LogUtil.d("gotResult" + s);
            }
        });

//        initGps();

        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new PermissionsResultAction() {

                    @Override
                    public void onGranted() {
//
//                        mLocationClient.start();
                    }

                    @Override
                    public void onDenied(String permission) {
                        AndroidUtil.toast("亲请允许定位权限");
                    }
                });

        if (null == mWebSocketClient || mWebSocketClient.getConnection().isClosed()) {
            try {
                mWebSocketClient = new WebSocketUtil(new WebSocketCallback() {
                    @Override
                    public void onOpen(ServerHandshake handshake) {
                        super.onOpen(handshake);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mBtnLv.setText("webSocket已连接");
                            }
                        });

                        socketBuffter = new StringBuffer(256);
                    }

                    @Override
                    public void onMessage(String s) {
                        super.onMessage(s);
                        socketBuffter.append(s + "\n");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTv.setText(socketBuffter.toString());
                            }
                        });

                        if (s.equals("1")) {
                            mLocationClient.requestLocation();
                            mLocationClient.stop();
                        }

                    }

                    @Override
                    public void onClose(int i, String s, boolean b) {
                        super.onClose(i, s, b);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mBtnLv.setText("webSocket已关闭");
                            }
                        });

                    }
                });
                mWebSocketClient.connect();

            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }

        //banner显示
        List<String> list = new ArrayList<>();
        list.add("http://s2.boohee.cn/house/upload_food/2013/11/25/279461_1385346589.jpg");
        list.add("http://s2.boohee.cn/house/upload_food/2013/11/25/279461_1385346589.jpg");
        list.add("http://s2.boohee.cn/house/upload_food/2013/11/25/279461_1385346589.jpg");
//        mBanner.isAutoPlay(false);
//        mBanner.setDelayTime(1000);
        ImageUtil.startBanner(mBanner, list);
        mBanner.setOnBannerClickListener(new OnBannerClickListener() {
            @Override
            public void OnBannerClick(int position) {
                LogUtil.e(position + "点击事件");
            }
        });
        mBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                LogUtil.e(position+" onPageScrolled");
            }

            @Override
            public void onPageSelected(int position) {
//                LogUtil.e(position+" onPageSelected");
            }

            @Override
            public void onPageScrollStateChanged(int state) {
//                LogUtil.e(state+" onPageScrollStateChanged");
            }
        });


    }


    @OnClick({R.id.btn, R.id.btn_calendar, btn_lv, R.id.btn_img, R.id.btn_send_msg, R.id.baidu,R.id.btn_pop})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.baidu:
                String address = "address=吴中路1081号";
                /**调用百度地图Web页面
                 * address=LocaltionAddress&src=YourAppName
                 */
                String uristr = "http://api.map.baidu.com/geocoder?" + address
                        + "&output=html&src=yhc";
                Uri uri = Uri.parse(uristr);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);

                break;
            case R.id.btn:
                AndroidUtil.intentAct(getActivity(), RefreshAct.class);
                break;
            case R.id.btn_calendar:

//                View dialogView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_calendar, null);
//                DialogUtil.getInstance().showDialog(getActivity(), dialogView);
//                CalendarView mCalendarView = (CalendarView) dialogView.findViewById(R.id.calendarView);
//                mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
//                    @Override
//                    public void onSelectedDayChange(CalendarView view, int i, int i1, int i2) {
//
//                        mBtnCalendar.setText(i + "-" + (i1 + 1) + "-" + i2);//2016-9-11
//                    }
//
//                });

                AndroidUtil.intentAct(getActivity(), CalendarAct.class);

                break;
            case R.id.btn_lv:
//
                if (null != mWebSocketClient) {

                    if (mWebSocketClient.getConnection().isOpen()) {
                        mWebSocketClient.close();
                    } else {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                mWebSocketClient.run();
                            }
                        }).start();
                    }

                }


                break;
            case R.id.btn_send_msg://发送消息
                if (null != mWebSocketClient && mWebSocketClient.getConnection().isOpen()) {
                    WebSocketMsg msg = new WebSocketMsg();
                    msg.setShopId("1");
                    msg.setSuggestContent(new Date() + "\n消息:" + StringUtil.getEditText(mEdtMsg) + "\n");
                    mWebSocketClient.send(jsonUtil.toJson(msg));
                    mEdtMsg.setText("");
                }


                break;
            case R.id.btn_img:
                ImageUtil.setImage(getActivity(), mSdv, "http://s2.boohee.cn/house/upload_food/2013/11/25/279461_1385346589.jpg");
                ImageUtil.setImageRes(mSdv1, R.mipmap.app_icon);
                mSdv.setVisibility(View.VISIBLE);
                mSdv1.setVisibility(View.VISIBLE);


//                HttpSender.getInstance().setContext(getActivity()).setHttpMode(HttpMode.FREE).setUrl("http://192.168.31.105:8080/test/customerOrderList?customer_id=2").setCallback(new StringCallback() {
//                    @Override
//                    public void onResponse(String response) {
//                        LogUtil.d(response);
//
//                    }
//                }).sender();

//                AndroidUtil.intentAct(getActivity(),Add.class);


                break;

            case R.id.btn_pop:
                AndroidUtil.intentAct(getActivity(),PopAct.class);

                break;
        }
    }

    private void baseVoid() {
        SpUtil.clear();//清空share缓存

        User user = new User();
        user.setUserName("杨须彬");
        user.setUserAge(18);

        String json = jsonUtil.toJson(user);

        LogUtil.d("json: " + json);

        User _user = json2Bean(json, User.class);

        LogUtil.d("_user: " + _user.toString());

        Map<String, Object> map;
        map = jsonUtil.json2Map(json);

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            SpUtil.put(entry.getKey(), entry.getValue());//share缓存
        }


        LogUtil.d(ScreenUtil.getDensity() + "");//获取屏幕密度


        String getJson = toJson(SpUtil.getAll());

        mTv.setText(jsonUtil.format(getJson));//转json对象
    }


    public LocationClient mLocationClient = null;

    /**
     * 初始化定位
     */
    private void initGps() {


//        LatLng p1 = new LatLng(121.42995, 31.217407);
//        LatLng p2 = new LatLng(121.38513, 31.180773);
//
//        LogUtil.d(DistanceUtil.getDistance(p1, p2) + "米");

        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
//                setMap(location.getLongitude() + "", location.getLatitude() + "");

                //Receive Location
                StringBuffer sb = new StringBuffer(256);
                sb.append("time : ");
                sb.append(location.getTime());
                sb.append("\nerror code : ");
                sb.append(location.getLocType());
                sb.append("\nlatitude : ");
                sb.append(location.getLatitude() + "");
                sb.append("\nlontitude : ");
                sb.append(location.getLongitude() + "");
                sb.append("\nradius : ");
                sb.append(location.getRadius());
                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                    sb.append("\nspeed : ");
                    sb.append(location.getSpeed());// 单位：公里每小时
                    sb.append("\nsatellite : ");
                    sb.append(location.getSatelliteNumber());
                    sb.append("\nheight : ");
                    sb.append(location.getAltitude());// 单位：米
                    sb.append("\ndirection : ");
                    sb.append(location.getDirection());// 单位度
                    sb.append("\naddr : ");
                    sb.append(location.getAddrStr());
                    sb.append("\ndescribe : ");
                    sb.append("gps定位成功");

                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                    sb.append("\naddr : ");
                    sb.append(location.getAddrStr());
                    //运营商信息
                    sb.append("\noperationers : ");
                    sb.append(location.getOperators());
                    sb.append("\ndescribe : ");
                    sb.append("网络定位成功");
                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                    sb.append("\ndescribe : ");
                    sb.append("离线定位成功，离线定位结果也是有效的");
                } else if (location.getLocType() == BDLocation.TypeServerError) {
                    sb.append("\ndescribe : ");
                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    sb.append("\ndescribe : ");
                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    sb.append("\ndescribe : ");
                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                }
                sb.append("\nlocationdescribe : ");
                sb.append(location.getLocationDescribe());// 位置语义化信息
                List<Poi> list = location.getPoiList();// POI数据
                if (list != null) {
                    sb.append("\npoilist size = : ");
                    sb.append(list.size());
                    for (Poi p : list) {
                        sb.append("\npoi= : ");
                        sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                    }
                }
                LogUtil.d("BaiduLocationApiDemo: " + sb.toString());
//                mTv.setText(sb.toString());
                Location nowLocation = new Location();
                nowLocation.setCreatetime(new Date());
                nowLocation.setLat(location.getLatitude() + "");
                nowLocation.setLng(location.getLongitude() + "");
                if (null != mWebSocketClient && mWebSocketClient.getConnection().isOpen()) {
                    mWebSocketClient.send(jsonUtil.toJson(nowLocation));
                }


            }
        });    //注册监听函数

        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
//        option.setScanSpan(0);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        mLocationClient.setLocOption(option);


    }


    /**
     * 提交位置信息
     *
     * @param lng
     * @param lat
     */
    private void setMap(String lng, String lat) {

        com.lex.cheeseStrip.bean.Map map = new com.lex.cheeseStrip.bean.Map();
        map.setLng(lng);
        map.setLat(lat);

        HttpSender sender = HttpSender.getInstance().setUrl("http://139.196.216.185/rexdb/setMap").setObj(map);
        sender.sender();

    }


}
